﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using thinger.DataConvertLib;

namespace Manson.CommonApi.Controllers
{
    /// <summary>
    /// 文件服务器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly string _storagePath = Path.Combine(Directory.GetCurrentDirectory(), "Files");
        public FileController()
        {
            if(!Directory.Exists(_storagePath))
            {
                Directory.CreateDirectory(_storagePath);
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost(Name= "UpLoad")]
        public async Task<OperateResult> UpLoad(IFormFile file)
        {
            if(file==null||file.Length==0)
            {
                return  OperateResult.CreateFailResult("上传文件不能为空！");
            }

            var fileName=ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Value.Trim('"');
            var filePath=Path.Combine(_storagePath, fileName);
            using (var stream=new FileStream(filePath,FileMode.Create))
            {
                await file.CopyToAsync (stream);
            }

            return OperateResult.CreateSuccessResult();
        }


        [HttpGet("{fileName}")]
        public IActionResult Download(string fileName)
        {
            var filePath = Path.Combine(_storagePath, fileName);
            if (!System.IO.File.Exists(filePath))
                return NotFound();

            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var contentType = "application/octet-stream"; // 通用二进制流
            return File(fileStream, contentType, fileName);
        }

    }
}
